package com.lykj.modules.shop.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.lykj.common.cache.CateCache;
import com.lykj.common.cache.ParamCache;
import com.lykj.core.log.exception.ServiceException;
import com.lykj.core.log.logger.LykjLogger;
import com.lykj.core.secure.utils.AuthUtil;
import com.lykj.core.tool.api.IResultCode;
import com.lykj.core.tool.api.R;
import com.lykj.core.tool.api.ResultCode;
import com.lykj.core.tool.support.Kv;
import com.lykj.core.tool.utils.DigestUtil;
import com.lykj.core.tool.utils.Func;
import com.lykj.modules.shop.entity.StoreCategory;
import com.lykj.modules.shop.entity.StoreProduct;
import com.lykj.modules.shop.entity.UserBill;
import com.lykj.modules.shop.entity.UserOrder;
import com.lykj.modules.shop.service.SMSService;
import com.lykj.modules.shop.service.StoreProductService;
import com.lykj.modules.shop.service.UserBillService;
import com.lykj.modules.shop.service.UserOrderService;
import com.lykj.modules.shop.znapi.ZnApiUtils;
import com.lykj.modules.system.entity.User;
import com.lykj.modules.system.entity.UserAddress;
import com.lykj.modules.system.service.DeptService;
import com.lykj.modules.system.service.ParamService;
import com.lykj.modules.system.service.UserAddressService;
import com.lykj.modules.system.service.UserService;
import io.swagger.annotations.*;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 众鸟接口 控制器
 *
 * @author cxl
 * @since 2022-01-14
 */
@RestController
@AllArgsConstructor
@RequestMapping("lykj-shop/zn")
@Api(value = "众鸟平台接口", tags = "众鸟平台接口")
public class LykjZNApiController {
	private final UserService userService;
	private final StoreProductService storeProductService;
	private final UserOrderService userOrderService;
	private final ZnApiUtils znApiUtils;
	private final UserBillService userBillService;
	private final ParamService paramService;
	private final LykjLogger logger; // 通用日志
	private final UserAddressService userAddressService; // 收货地址
	private final SMSService smsService; // 短信服务

	/**
	 * 登录
	 */
	@PostMapping("/loginByPwd")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "登录")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "username", value = "手机号", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "password", value = "新密码", paramType = "query", required = true, dataType = "String")
	})
	public R<JSONObject> loginByPwd(@ApiIgnore @RequestBody Map<String, Object> params) {
		String username = params.get("username").toString();
		String password = params.get("password").toString();
		JSONObject returnJson = znApiUtils.loginByPwd(username, password);
		logger.info("loginByPwd", returnJson.toJSONString());// 通用日志
		if ("200".equals(returnJson.getString("status")) && returnJson.getJSONObject("content") instanceof JSONObject) {
			JSONObject content = returnJson.getJSONObject("content");
			userService.update(Wrappers.<User>update().lambda().set(User::getZnUserId, content.getString("userId")).set(User::getZnToken, content.getString("token")).eq(User::getId, 1123598821738675201L));
		}
		return R.data(returnJson.getInteger("status"), returnJson, returnJson.getJSONObject("content").get("msg") != null ? returnJson.getJSONObject("content").getString("msg") : "操作成功");
	}

	/**
	 * 注册时发送验证码
	 */
	@PostMapping("/sendRegisterVerifyCode")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "注册时发送验证码")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "mobilePhone", value = "手机号", paramType = "query", required = true, dataType = "String")
	})
	public R<JSONObject> sendRegisterVerifyCode(@ApiIgnore @RequestBody Map<String, Object> params) {
		String mobilePhone = params.get("mobilePhone").toString();
		User user = userService.userByAccount("000000", mobilePhone);
		if(user!=null){
			throw new ServiceException("手机号已注册!");
		}
		smsService.sendRegisterVerifyCode(mobilePhone);
		logger.info("sendRegisterVerifyCode", mobilePhone);// 通用日志
		return R.success("发送成功");
	}

	/**
	 * 设置新登录密码
	 */
	@PostMapping("/resetLoginPwd")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "设置新登录密码")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "mobilePhone", value = "手机号", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "password", value = "新密码", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "verifyCode", value = "手机验证码", paramType = "query", required = true, dataType = "String")
	})
	public R<JSONObject> resetLoginPwd(@ApiIgnore @RequestBody Map<String, Object> params) {
		String mobilePhone = params.get("mobilePhone").toString();
		String password = params.get("password").toString();
		String verifyCode = params.get("verifyCode").toString();
		logger.info("resetLoginPwd", mobilePhone+" : "+verifyCode);// 通用日志
		boolean b = smsService.verificationVerifyCode(mobilePhone, verifyCode);
		if (b) {
			userService.update(Wrappers.<User>update().lambda().set(User::getPassword, DigestUtil.hex(password)).eq(User::getAccount, mobilePhone));
		}
		return R.success("设置新登录密码成功!");
	}

	/**
	 * 忘记登录密码发送验证码
	 */
	@PostMapping("/sendVerifyCode")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "忘记登录密码发送验证码")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "mobilePhone", value = "手机号", paramType = "query", required = true, dataType = "String")
	})
	public R<JSONObject> sendVerifyCode(@ApiIgnore @RequestBody Map<String, Object> params) {
		String mobilePhone = params.get("mobilePhone").toString();
		User user = userService.userByAccount("000000", mobilePhone);
		if(user==null){
			throw new ServiceException("用户未注册");
		}
		smsService.sendVerifyCode(mobilePhone);
		logger.info("sendVerifyCode", mobilePhone);// 通用日志
		return R.success("发送成功");
	}

	/**
	 * 修改昵称
	 */
	@PostMapping("/updateNickName")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改昵称")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "nickName", value = "昵称", paramType = "query", required = true, dataType = "String")
	})
	public R<JSONObject> updateNickName(@ApiIgnore @RequestBody Map<String, Object> params) {
		String nickName = params.get("nickName").toString();
		User user = userService.getById(AuthUtil.getUserId());
		user.setName(nickName);
		userService.updateById(user);
		JSONObject returnJson = znApiUtils.updateNickName(user.getZnToken(), user.getZnUserId(), nickName);
		logger.info("updateNickName", returnJson.toJSONString());// 通用日志
		return R.data(returnJson.getInteger("status"), returnJson, returnJson.getJSONObject("content").get("msg") != null ? returnJson.getJSONObject("content").getString("msg") : "操作成功");
	}

	/**
	 * 修改手机号
	 */
	@PostMapping("/modifyMobilePhone")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "修改手机号")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "mobilePhone", value = "手机号", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "verifyCode", value = "昵称", paramType = "query", required = true, dataType = "String")
	})
	public R<JSONObject> modifyMobilePhone(@ApiIgnore @RequestBody Map<String, Object> params) {
		String mobilePhone = params.get("mobilePhone").toString();
		String verifyCode = params.get("verifyCode").toString();
		User user = userService.getById(AuthUtil.getUserId());
		logger.info("modifyMobilePhone", JSON.toJSONString(user));// 通用日志
		if (smsService.verificationCustomerVerifyCode(mobilePhone,verifyCode)) {
			user.setAccount(mobilePhone);
			user.setPhone(mobilePhone);
			userService.updateById(user);
		}
		return R.success("修改手机号成功");
	}

	/**
	 * 修改手机号
	 */
	@PostMapping("/bindWechat")
	@ApiOperation(value = "绑定微信")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "openid", value = "手机号", paramType = "query", required = true, dataType = "String")
	})
	public R<JSONObject> bindWechat(@ApiIgnore @RequestBody Map<String, Object> params) {
		String openid = params.get("openid").toString();
		User user = userService.getById(AuthUtil.getUserId());
		logger.info("openid", JSON.toJSONString(user));// 通用日志
		user.setOpenid(openid);
		userService.updateById(user);
		return R.success("绑定微信成功");
	}

	/**
	 * 绑定手机号发送验证码
	 */
	@PostMapping("/sendCustomerVerifyCode")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "绑定手机号发送验证码")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "mobilePhone", value = "手机号", paramType = "query", required = true, dataType = "String")
	})
	public R<JSONObject> sendCustomerVerifyCode(@ApiIgnore @RequestBody Map<String, Object> params) {
		String mobilePhone = params.get("mobilePhone").toString();
		User user = userService.getById(AuthUtil.getUserId());
		logger.info("sendCustomerVerifyCode", JSON.toJSONString(user));// 通用日志
		smsService.sendCustomerVerifyCode(mobilePhone);
		return R.success("发送成功");
	}

	/**
	 * 用户实名申请
	 */
	@PostMapping("/authenticationApply")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "用户实名申请")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "backDocument", value = "证件照(反面)地址", paramType = "query", required = true, dataType = "int"),
		@ApiImplicitParam(name = "documentNumber", value = "证件号码", paramType = "query", required = true, dataType = "int"),
		@ApiImplicitParam(name = "documentType", value = "证件类型cardType", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "frontDocument", value = "证件照(正面)地址", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "handDocument", value = "证件照(手持)地址", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "realName", value = "真实姓名", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "realName", value = "证件有效期", paramType = "query", required = true, dataType = "String")
	})
	public R<JSONObject> authenticationApply(@ApiIgnore @RequestBody Map<String, Object> params) {
		if (Func.isNull(params) || params.toString().indexOf("*") > -1) {// || params.toString().indexOf(" ") > -1
			throw new ServiceException("请认真检查填写相关信息，确保信息正确有效!");
		}
		User user = userService.getById(AuthUtil.getUserId());
		JSONObject returnJson = znApiUtils.authenticationApply(user.getZnToken(), user.getZnUserId(), params);
		logger.info("authenticationApply", returnJson.toJSONString());// 通用日志
		// 不能直接修改状态 需要审核
		if ("200".equals(returnJson.getString("status"))) {
			String realName = params.get("realName").toString();
			znApiUtils.updateNickName(user.getZnToken(), user.getZnUserId(), realName);
		}
		return R.data(returnJson.getInteger("status"), returnJson, returnJson.getJSONObject("content").get("msg") != null ? returnJson.getJSONObject("content").getString("msg") : "操作成功");
	}

	/**
	 * 上传实名申请证件照
	 */
	@SneakyThrows
	@PostMapping("/uploadApplyPhoto")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "上传实名申请证件照")
	public R<JSONObject> uploadApplyPhoto(@ApiParam(value = "附件文件", required = true) @RequestBody MultipartFile file) {
		User user = userService.getById(AuthUtil.getUserId());
		JSONObject returnJson = znApiUtils.uploadApplyPhoto(user.getZnToken(), user.getZnUserId(), file);
		logger.info("uploadApplyPhoto", returnJson.toJSONString());// 通用日志
		return R.data(returnJson.getInteger("status"), returnJson, returnJson.getJSONObject("content").get("msg") != null ? returnJson.getJSONObject("content").getString("msg") : "操作成功");
	}

	/**
	 * 实名查询
	 */
	@GetMapping("/authenticationInfo")
	@ApiOperationSupport(order = 10)
	@ApiOperation(value = "实名查询")
	public R<JSONObject> authenticationInfo() {
		User user = userService.getById(AuthUtil.getUserId());
		JSONObject returnJson = znApiUtils.authenticationInfo(user.getZnToken(), user.getZnUserId());
		logger.info("authenticationInfo", returnJson.toJSONString());// 通用日志
		if ("200".equals(returnJson.getString("status")) && returnJson.getJSONObject("content") instanceof JSONObject) {
			if (returnJson.getJSONObject("content").get("status") != null && "2".equals(returnJson.getJSONObject("content").getString("status"))) {
				user.setZnAuthenticationed("true");
				userService.updateById(user);
			}
		}
		return R.data(returnJson.getInteger("status"), returnJson, returnJson.getJSONObject("content").get("msg") != null ? returnJson.getJSONObject("content").getString("msg") : "操作成功");
	}

	/**
	 * 设置/重置安全密码
	 */
	@PostMapping("/fundPasswordReset")
	@ApiOperationSupport(order = 11)
	@ApiOperation(value = "设置/重置安全密码")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "documentNumber", value = "证件号码", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "documentType", value = "证件类型 cardType", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "fundPassword", value = "新安全密码！不允许为空，客户端限制 6位纯数字，需要在客户端对新安全密码进行 MD5 加密后传到服务端", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "realName", value = "真实姓名", paramType = "query", required = true, dataType = "String")
	})
	public R<JSONObject> fundPasswordReset(@ApiIgnore @RequestBody Map<String, Object> params) {
		User user = userService.getById(AuthUtil.getUserId());
		JSONObject returnJson = znApiUtils.fundPasswordReset(user.getZnToken(), user.getZnUserId(), params);
		logger.info("fundPasswordReset", returnJson.toJSONString());// 通用日志
		if ("200".equals(returnJson.getString("status"))) {
			user.setZnFundPasswordSet("true");
			userService.updateById(user);
		}
		return R.data(returnJson.getInteger("status"), returnJson, returnJson.getJSONObject("content").get("msg") != null ? returnJson.getJSONObject("content").getString("msg") : "操作成功");
	}

	/**
	 * 查询个人信息
	 */
	@GetMapping("/customerInfo")
	@ApiOperationSupport(order = 12)
	@ApiOperation(value = "查询个人信息")
	public R<JSONObject> customerInfo() {
		User user = userService.getById(AuthUtil.getUserId());
		JSONObject returnJson = znApiUtils.customerInfo(user.getZnToken(), user.getZnUserId());
		logger.info("customerInfo", returnJson.toJSONString());// 通用日志
		return R.data(returnJson.getInteger("status"), returnJson, returnJson.getJSONObject("content").get("msg") != null ? returnJson.getJSONObject("content").getString("msg") : "操作成功");
	}

	/**
	 * 添加收货地址
	 */
	@PostMapping("/shippingAddressAdd")
	@ApiOperationSupport(order = 13)
	@ApiOperation(value = "添加收货地址")
	public R<UserAddress> shippingAddressAdd(@ApiParam(value = "{\"city\":\"城市\",\"contacts\":\"联系人\",\"county\":\"县区\",\"detailedAddress\":\"详细地址\",\"isDefault\":默认true,\"mobile\":\"联系电话\",\"name\":\"别名\",\"province\":\"省份\"}", required = true) @RequestBody String jsonObject) {
		if(AuthUtil.getUserId() < 1){
			return R.fail(ResultCode.CLIENT_UN_AUTHORIZED);
		}
		logger.warn("shippingAddressAdd: [warn] " , jsonObject);// 通用日志
		logger.error("shippingAddressAdd: [error]" , jsonObject);// 通用日志
		UserAddress userAddress = JSON.parseObject(jsonObject,UserAddress.class);
		userAddress = userAddressService.shippingAddressAdd(userAddress);
		R<UserAddress> status = R.status(true);
		status.setData(userAddress);
		logger.info("shippingAddressAdd", JSON.toJSONString(status));// 通用日志
		return status;
	}

	/**
	 * 设为默认收货地址
	 */
	@PostMapping("/shippingAddressAsDefault")
	@ApiOperationSupport(order = 14)
	@ApiOperation(value = "设为默认收货地址")
	public R<Boolean> shippingAddressAsDefault(@ApiParam(value = "地址ID", required = true) @RequestParam String addressId) {
		if(AuthUtil.getUserId() < 1){
			return R.fail(ResultCode.CLIENT_UN_AUTHORIZED);
		}
		R<Boolean> status = R.status(userAddressService.shippingAddressAsDefault(addressId));
		logger.info("shippingAddressAsDefault", JSON.toJSONString(status));// 通用日志
		return status;
	}

	/**
	 * 删除收货地址
	 */
	@PostMapping("/shippingAddressDelete")
	@ApiOperationSupport(order = 15)
	@ApiOperation(value = "删除收货地址")
	public R shippingAddressDelete(@ApiParam(value = "地址ID", required = true) @RequestParam String addressId) {
		if(AuthUtil.getUserId() < 1){
			return R.fail(ResultCode.CLIENT_UN_AUTHORIZED);
		}
		R<Boolean> status = R.status(userAddressService.shippingAddressDelete(addressId));
		logger.info("shippingAddressDelete", JSON.toJSONString(status));// 通用日志
		return status;
	}

	/**
	 * 查询收货地址列表
	 */
	@GetMapping("/addressList")
	@ApiOperationSupport(order = 16)
	@ApiOperation(value = "查询收货地址列表")
	public R<Kv> addressList() {
		if(AuthUtil.getUserId() < 1){
			return R.fail(ResultCode.CLIENT_UN_AUTHORIZED);
		}
		List<UserAddress> list = userAddressService.addressList(AuthUtil.getUserId());
		R<Kv> status = R.status(true);
		Kv content = Kv.create().set("content", list);
		status.setData(content);
		logger.info("addressList", JSON.toJSONString(status));// 通用日志
		return status;
	}

	/**
	 * 绑定银行账户
	 */
	@PostMapping("/bindAccountBind")
	@ApiOperationSupport(order = 17)
	@ApiOperation(value = "绑定银行账户")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "account", value = "银行账号", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "bankNO", value = "超级网银号", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "bankName", value = "银行名称", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "documentNumber", value = "证件号码", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "documentType", value = "证件类型 documentType", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "mobilePhone", value = "银行预留手机号", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "realName", value = "真实姓名", paramType = "query", required = true, dataType = "String")
	})
	public R<JSONObject> bindAccountBind(@ApiIgnore @RequestBody Map<String, Object> params) {
		User user = userService.getById(AuthUtil.getUserId());
		JSONObject returnJson = znApiUtils.bindAccountBind(user.getZnToken(), user.getZnUserId(), params);
		logger.info("bindAccountBind", returnJson.toJSONString());// 通用日志
		if ("200".equals(returnJson.getString("status"))) {
			user.setZnIsBindCard(1);
			userService.updateById(user);
		}
		return R.data(returnJson.getInteger("status"), returnJson, "操作成功");
	}

	/**
	 * 验证绑定信息
	 */
	@PostMapping("/bindVerification")
	@ApiOperationSupport(order = 18)
	@ApiOperation(value = "验证绑定信息")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "bindRecordId", value = "绑定记录编号", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "orderNo", value = "鉴权序号，金额鉴权时必传", paramType = "query", required = false, dataType = "String"),
		@ApiImplicitParam(name = "smsVerificationCode", value = "短信验证码，短信验证时必传", paramType = "query", required = false, dataType = "String"),
		@ApiImplicitParam(name = "verificationAmount", value = "鉴权金额，金额鉴权时必传", paramType = "query", required = false, dataType = "String")
	})
	public R<JSONObject> bindVerification(@ApiIgnore @RequestBody Map<String, Object> params) {
		User user = userService.getById(AuthUtil.getUserId());
		JSONObject returnJson = znApiUtils.bindVerification(user.getZnToken(), user.getZnUserId(), params);
		logger.info("bindVerification", returnJson.toJSONString());// 通用日志
		if ("200".equals(returnJson.getString("status"))) {
			user.setZnIsBindCard(1);
			userService.updateById(user);
		}
		return R.data(returnJson.getInteger("status"), returnJson, returnJson.getJSONObject("content").get("msg") != null ? returnJson.getJSONObject("content").getString("msg") : "操作成功");
	}

	/**
	 * 解绑银行账户
	 */
	@PostMapping("/bindAccountUnBind")
	@ApiOperationSupport(order = 19)
	@ApiOperation(value = "解绑银行账户")
	public R<JSONObject> bindAccountUnBind(@ApiParam(value = "绑定ID", required = true) @RequestParam String id) {
		User user = userService.getById(AuthUtil.getUserId());
		JSONObject returnJson = znApiUtils.bindAccountUnBind(user.getZnToken(), user.getZnUserId(), id);
		logger.info("bindAccountUnBind", returnJson.toJSONString());// 通用日志
		return R.data(returnJson.getInteger("status"), returnJson, "操作成功");
	}

	/**
	 * 查询绑定银行账号
	 */
	@GetMapping("/bindAccountList")
	@ApiOperationSupport(order = 20)
	@ApiOperation(value = "查询绑定银行账号")
	public R<JSONObject> bindAccountList() {
//		User user = userService.getById(AuthUtil.getUserId());
		JSONObject returnJson = JSON.parseObject("{\"content\":[]}"); //znApiUtils.bindAccountList(user.getZnToken(), user.getZnUserId());
		logger.info("bindAccountList", returnJson.toJSONString());// 通用日志
//		return R.data(returnJson.getInteger("status"), returnJson, "操作成功");
		return R.data(200, returnJson, "操作成功");
	}

	/**
	 * 充值申请
	 */
	@PostMapping("/recharge")
	@ApiOperationSupport(order = 21)
	@ApiOperation(value = "充值申请")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "amount", value = "充值金额", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "payMode", value = "支付方式 app支付-支付宝:ali_app 微信:wechat_app", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "payTypeId", value = "充值方式 payType (1:支付宝、2:微信)", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "requestAttach", value = "扩展字段  {\"subject\":\"充值\"} %7B%22subject%22:%22%E5%85%85%E5%80%BC%22%7D", paramType = "query", required = true, dataType = "String")
	})
	public R<JSONObject> recharge(@ApiIgnore @RequestBody Map<String, Object> params) {
		String withdrawalStatus = paramService.getValue("zn.pay.status");
		if (!"true".equals(withdrawalStatus)) {
			String withdrawalMsg = paramService.getValue("zn.pay.msg");
			throw new ServiceException(withdrawalMsg);
		}
		User user = userService.getById(AuthUtil.getUserId());
		JSONObject returnJson = znApiUtils.recharge(user.getZnToken(), user.getZnUserId(), params);
		logger.info("recharge", returnJson.toJSONString());// 通用日志
		return R.data(returnJson.getInteger("status"), returnJson, returnJson.getJSONObject("content").get("msg") != null ? returnJson.getJSONObject("content").getString("msg") : "操作成功");
	}

	/**
	 * 查询充值列表
	 */
	@GetMapping("/rechargeList")
	@ApiOperationSupport(order = 22)
	@ApiOperation(value = "查询充值列表")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "month", value = "查询月份 格式:2020-08", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "offset", value = "查询偏移量，正值查询新增，负值查询过去数据", paramType = "query", required = true, dataType = "int"),
		@ApiImplicitParam(name = "standard", value = "查询基准号，本服务中定义为充值编号", paramType = "query", required = false, dataType = "String"),
		@ApiImplicitParam(name = "status", value = "状态（1：支付中，2：支付成功，3：支付失败，4：已关闭）", paramType = "query", required = false, dataType = "String")
	})
	public R<JSONObject> rechargeList(@ApiIgnore @RequestParam Map<String, Object> params) {
		User user = userService.getById(AuthUtil.getUserId());
		JSONObject returnJson = znApiUtils.rechargeList(user.getZnToken(), user.getZnUserId(), params);
		logger.info("rechargeList", returnJson.toJSONString());// 通用日志
		return R.data(returnJson.getInteger("status"), returnJson, "操作成功");
	}

	/**
	 * 提现申请
	 */
	@PostMapping("/withdrawal")
	@ApiOperationSupport(order = 23)
	@ApiOperation(value = "提现申请")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "amount", value = "提现金额", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "fundPassword", value = "安全密码，需要在客户端对密码进行 MD5 加密后传到服务端", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "payTypeId", value = "提现方式 payType (1:支付宝、2:微信)", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "payeeAttach", value = "收款信息 收款信息{\"payee_account\":\"支付宝账号\", \"payee_real_name\":\"真实姓名\",\"remark \":\"备注\"} encode", paramType = "query", required = true, dataType = "String")
	})
	public R<JSONObject> withdrawal(@ApiIgnore @RequestBody Map<String, Object> params) {
		String withdrawalStatus = paramService.getValue("zn.pay.status");
		if (!"true".equals(withdrawalStatus)) {
			String withdrawalMsg = paramService.getValue("zn.pay.msg");
			throw new ServiceException(withdrawalMsg);
		}
		String ids = ParamCache.getValue("withdrawal.ban");
		User user = userService.getById(AuthUtil.getUserId());
		if(ids.indexOf(user.getId().toString())>-1){
			return R.fail("该功能暂未解锁！");
		}
//		User user = userService.getById(AuthUtil.getUserId());
		JSONObject returnJson = znApiUtils.withdrawal(user.getZnToken(), user.getZnUserId(), params);
		logger.info("withdrawal", returnJson.toJSONString());// 通用日志
		return R.data(returnJson.getInteger("status"), returnJson, returnJson.getJSONObject("content").get("msg") != null ? returnJson.getJSONObject("content").getString("msg") : "操作成功");
	}

	/**
	 * 查询提现列表
	 */
	@GetMapping("/withdrawalList")
	@ApiOperationSupport(order = 24)
	@ApiOperation(value = "查询提现列表")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "month", value = "查询月份 格式:2020-08", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "offset", value = "查询偏移量，正值查询新增，负值查询过去数据", paramType = "query", required = true, dataType = "int"),
		@ApiImplicitParam(name = "standard", value = "查询基准号，本服务中定义为充值编号", paramType = "query", required = false, dataType = "String"),
		@ApiImplicitParam(name = "status", value = "状态（1：支付中，2：支付成功，3：支付失败，4：已关闭）", paramType = "query", required = false, dataType = "String")
	})
	public R<JSONObject> withdrawalList(@ApiIgnore @RequestParam Map<String, Object> params) {
		User user = userService.getById(AuthUtil.getUserId());
//		JSONObject returnJson = znApiUtils.withdrawalList(user.getZnToken(), user.getZnUserId(), params);
		params.put("catalogId", "10402");
		JSONObject returnJson = znApiUtils.fundsFlowQueryList(user.getZnToken(), user.getZnUserId(), params);
		logger.info("withdrawalList", returnJson.toJSONString());// 通用日志
		return R.data(returnJson.getInteger("status"), returnJson, "操作成功");
	}

	/**
	 * 查询用户余额
	 */
	@GetMapping("/balanceQuery")
	@ApiOperationSupport(order = 25)
	@ApiOperation(value = "查询用户余额")
	public R<JSONObject> balanceQuery() {
		User user = userService.getById(AuthUtil.getUserId());
		JSONObject returnJson = znApiUtils.balanceQuery(user.getZnToken(), user.getZnUserId());
		logger.info("balanceQuery", returnJson.toJSONString());// 通用日志
		if ("200".equals(returnJson.getString("status")) && returnJson.getJSONObject("content") instanceof JSONObject) {
			User userTemp = new User();
			userTemp.setId(user.getId());
			userTemp.setZnBalance(returnJson.getJSONObject("content").getString("balance"));
			userService.updateById(user);
		}
		return R.data(returnJson.getInteger("status"), returnJson, returnJson.getJSONObject("content").get("msg") != null ? returnJson.getJSONObject("content").getString("msg") : "操作成功");
	}

	/**
	 * 查询是否签约
	 */
	@GetMapping("/querySignContract")
	@ApiOperationSupport(order = 26)
	@ApiOperation(value = "查询是否签约")
	public R<JSONObject> querySignContract() {
		User user = userService.getById(AuthUtil.getUserId());
		JSONObject returnJson = znApiUtils.querySignContract(user.getZnToken(), user.getZnUserId());
		logger.info("querySignContract", returnJson.toJSONString());// 通用日志
		if ("200".equals(returnJson.getString("status")) && returnJson.getJSONObject("content") instanceof JSONObject) {
			user.setZnSignContract(returnJson.getJSONObject("content").getString("responseValue"));
			userService.updateById(user);
		}
		return R.data(returnJson.getInteger("status"), returnJson, returnJson.getJSONObject("content").get("msg") != null ? returnJson.getJSONObject("content").getString("msg") : "操作成功");
	}

	/**
	 * 签约申请
	 */
	@PostMapping("/signContract")
	@ApiOperationSupport(order = 27)
	@ApiOperation(value = "签约申请")
	public R<JSONObject> signContract(@ApiParam(value = "回调地址", required = true) @RequestBody String callbackUrl) {
		String callback = ParamCache.getValue("signContract.callbackUrl");
		User user = userService.getById(AuthUtil.getUserId());
		JSONObject returnJson = znApiUtils.signContract(user.getZnToken(), user.getZnUserId(), callback);
		logger.info("signContract", returnJson.toJSONString());// 通用日志
		return R.data(returnJson.getInteger("status"), returnJson, returnJson.getJSONObject("content").get("msg") != null ? returnJson.getJSONObject("content").getString("msg") : "操作成功");
	}

	/**
	 * 签约协议确认
	 */
	@PostMapping("/registerSure")
	@ApiOperationSupport(order = 28)
	@ApiOperation(value = "签约协议确认")
	public R<JSONObject> registerSure(@ApiParam(value = "签约渠道(手机端：APP，PC：H5)", required = true) @RequestBody String channel) {
		User user = userService.getById(AuthUtil.getUserId());
		JSONObject returnJson = znApiUtils.registerSure(user.getZnToken(), user.getZnUserId(), channel);
		logger.info("registerSure", returnJson.toJSONString());// 通用日志
		return R.data(returnJson.getInteger("status"), returnJson, returnJson.getJSONObject("content").get("msg") != null ? returnJson.getJSONObject("content").getString("msg") : "操作成功");
	}

	/**
	 * 摘单
	 */
	@PostMapping("/tradeBatch")
	@ApiOperationSupport(order = 29)
	@ApiOperation(value = "摘单")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "productId", value = "商品ID", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "commodityId", value = "商品ID", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "tradeBatchVO", value = "{\"addressId\":109,\"bankId\":47,\"bankNO\":\"307584007998\",\"callbackUrl\":\"www.baidu.com\",\"commodityId\":\"G00006\",\"makerId\":157,\"payType\":支付方式（0：余额支付 1：三方支付）,\"quantity\":1,\"tradeType\":交易方式（0：寄存 1：提货）,\"type\":\"1\"}", paramType = "query", required = true, dataType = "String"),
	})
	public R<JSONObject> tradeBatch(@ApiIgnore @RequestBody Map<String, Object> params) {
		JSONObject jsonObject = (JSONObject) JSONObject.toJSON(params.get("tradeBatchVO"));
		// TODO 商品购买数量
		Integer number = jsonObject.getInteger("quantity");
		if (Func.isNull(params.get("productId")) || number < 1) {
			throw new ServiceException("请选择商品！");
		}
		Long productId = Long.parseLong(params.get("productId").toString());
		// 商品信息
		StoreProduct storeProduct = storeProductService.getOne(Wrappers.<StoreProduct>lambdaQuery()
			.eq(StoreProduct::getTenantId, AuthUtil.getTenantId())
			.eq(StoreProduct::getId, productId));
		if (Func.isNull(storeProduct)) {
			throw new ServiceException("非法操作！");
		}
		User user = userService.getById(AuthUtil.getUserId());
		// TODO 订单运费
		BigDecimal orderPostage = storeProduct.getExpressFee().multiply(new BigDecimal(number));
		if (orderPostage.compareTo(BigDecimal.ZERO) > 0) {
			if (user.getSysBalance().compareTo(orderPostage) < 0) {
				throw new ServiceException("平台账户余额不足，无法完成购买");
			}
			// 从余额扣除运费
			userService.decBalance(orderPostage,user.getId());
		}
		// TODO 摘单
		JSONObject returnJson = znApiUtils.tradeBatch(user.getZnToken(), user.getZnUserId(), params.get("commodityId").toString(), jsonObject);
		logger.info("tradeBatch", returnJson.toJSONString());// 通用日志
		if ("200".equals(returnJson.getString("status")) && returnJson.getJSONObject("content") instanceof JSONObject) {
			// 生成订单
			UserOrder userOrder = userOrderService.insertMoneyOrder(user.getTenantId(),
				user.getId(),
				user.getRealName(),
				user.getAccount(),
				null,
				storeProduct,
				BigDecimal.valueOf(number),
				2,
				-1,
				null,
				"摘单");
			if (orderPostage.compareTo(BigDecimal.ZERO) > 0) {
				//运费扣除记录
				UserBill userBill = new UserBill();
				userBill.setTenantId(user.getTenantId());
				userBill.setUserId(user.getId());
				userBill.setOtherUserId(0L);
				userBill.setLinkId(userOrder.getId());
				userBill.setPm(0);//0转出1转入
				userBill.setNumber(orderPostage);
				userBill.setService(BigDecimal.ZERO);
				userBill.setActual(userBill.getNumber().add(userBill.getService()));
				userBill.setTitle("众鸟订单支付运费");
				userBill.setCategory(0);//0现金1积分2贡献值
				userBill.setType(10);//0增加1减少2奖励3兑换4充值5提现6购物7转账8红包9收益10运费
				userBill.setBalance(user.getSysBalance());
				userBill.setRemark("众鸟订单支付运费,运费[" + userBill.getNumber() + "],手续费[" + userBill.getService() + "],实际金额[" + userBill.getActual() + "],余额[" + userBill.getBalance() + "]");
				userBillService.save(userBill);
			}

			// TODO 激活分流平台 二级解冻资格
			if (userOrder.getTotalPrice().compareTo(BigDecimal.valueOf(299)) > -1) {
				znApiUtils.brokerageTwoStatus(user.getTenantId(), user.getAccount());
			}
		}
		return R.data(returnJson.getInteger("status"), returnJson, returnJson.getJSONObject("content").get("msg") != null ? returnJson.getJSONObject("content").getString("msg") : "操作成功");
	}

	/**
	 * 查询订单
	 */
	@GetMapping("/tradeList")
	@ApiOperationSupport(order = 30)
	@ApiOperation(value = "查询订单")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "bsFlag", value = "买卖标志（1买2卖）", paramType = "query", required = false, dataType = "String"),
		@ApiImplicitParam(name = "commodity", value = "商品（商品代码）", paramType = "query", required = false, dataType = "String"),
		@ApiImplicitParam(name = "endCreateTime", value = "结束日期 格式:2020-08-08", paramType = "query", required = false, dataType = "String"),
		@ApiImplicitParam(name = "offset", value = "查询偏移量，正值查询新增，负值查询过去数据", paramType = "query", required = true, dataType = "int"),
		@ApiImplicitParam(name = "standard", value = "查询基准号，本服务中定义为充值编号", paramType = "query", required = false, dataType = "String"),
		@ApiImplicitParam(name = "startCreateTime", value = "开始日期 格式:2020-08-08", paramType = "query", required = false, dataType = "String"),
		@ApiImplicitParam(name = "tradeType", value = "成交类型（1摘单成功2挂单成功）", paramType = "query", required = false, dataType = "String")
	})
	public R<JSONObject> tradeList(@ApiIgnore @RequestParam Map<String, Object> params) {
		User user = userService.getById(AuthUtil.getUserId());
		JSONObject returnJson = znApiUtils.tradeList(user.getZnToken(), user.getZnUserId(), params);
		logger.info("tradeList", returnJson.toJSONString());// 通用日志
		JSONObject returnJsonHis = znApiUtils.tradeListHis(user.getZnToken(), user.getZnUserId(), params);
		if (returnJson.getJSONObject("content").getJSONArray("list") == null) {
			returnJson.getJSONObject("content").put("list", returnJsonHis.getJSONArray("list"));
		} else {
			if (returnJsonHis.getJSONObject("content").getJSONArray("list") != null) {
				returnJson.getJSONObject("content").getJSONArray("list").addAll(returnJsonHis.getJSONObject("content").getJSONArray("list"));
			}
		}
		return R.data(returnJson.getInteger("status"), returnJson, "操作成功");
	}

	/**
	 * 申请交收
	 */
	@PostMapping("/deliveryApply")
	@ApiOperationSupport(order = 31)
	@ApiOperation(value = "申请交收")
	public R<JSONObject> deliveryApply(@ApiParam(value = "{\"addressId\":109,\"bankId\":47,\"bankNO\":\"307584007998\",\"commodityId\":\"G00006\",\"payType\":0,\"quantity\":1,\"type\":\"1\"}", required = true) @RequestBody JSONObject jsonObject) {
		User user = userService.getById(AuthUtil.getUserId());
		JSONObject returnJson = znApiUtils.deliveryApply(user.getZnToken(), user.getZnUserId(), jsonObject);
		logger.info("deliveryApply", returnJson.toJSONString());// 通用日志
		return R.data(returnJson.getInteger("status"), returnJson, returnJson.getJSONObject("content").get("msg") != null ? returnJson.getJSONObject("content").getString("msg") : "操作成功");
	}

	/**
	 * 查找交收申请信息
	 */
	@GetMapping("/deliveryList")
	@ApiOperationSupport(order = 32)
	@ApiOperation(value = "查找交收申请信息")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "commodity", value = "商品（商品代码或名称）", paramType = "query", required = false, dataType = "String"),
		@ApiImplicitParam(name = "endCreateTime", value = "结束日期 格式:2020-08-08", paramType = "query", required = false, dataType = "String"),
		@ApiImplicitParam(name = "offset", value = "查询偏移量，正值查询新增，负值查询过去数据", paramType = "query", required = true, dataType = "int"),
		@ApiImplicitParam(name = "standard", value = "查询基准号，本服务中定义为充值编号", paramType = "query", required = false, dataType = "String"),
		@ApiImplicitParam(name = "startCreateTime", value = "开始日期 格式:2020-08-08", paramType = "query", required = false, dataType = "String"),
		@ApiImplicitParam(name = "status", value = "状态 deliveryApplyStatus（0：申请 1：配送中 2：确认收货 3：用户取消 4：管理员取消", paramType = "query", required = false, dataType = "String")
	})
	public R<JSONObject> deliveryList(@ApiIgnore @RequestParam Map<String, Object> params) {
		User user = userService.getById(AuthUtil.getUserId());
		JSONObject returnJson = znApiUtils.deliveryList(user.getZnToken(), user.getZnUserId(), params);
		logger.info("deliveryList", returnJson.toJSONString());// 通用日志
		return R.data(returnJson.getInteger("status"), returnJson, "操作成功");
	}

	/**
	 * 确认收货
	 */
	@PostMapping("/deliveryConfirmReceipt")
	@ApiOperationSupport(order = 33)
	@ApiOperation(value = "确认收货")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "deliveryApplyId", value = "交收申请编号", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "commodityId", value = "众鸟商品ID", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "quantity", value = "数量", paramType = "query", required = true, dataType = "String")
	})
	public R<JSONObject> deliveryConfirmReceipt(@ApiIgnore @RequestBody Map<String, Object> params) {
		User user = userService.getById(AuthUtil.getUserId());
		String deliveryApplyId = params.get("deliveryApplyId").toString();
		JSONObject returnJson = znApiUtils.deliveryConfirmReceipt(user.getZnToken(), user.getZnUserId(), deliveryApplyId);
		logger.info("deliveryConfirmReceipt", returnJson.toJSONString());// 通用日志
		if ("200".equals(returnJson.getString("status"))) {
			List<UserOrder> listOrder = userOrderService.list(Wrappers.<UserOrder>lambdaQuery()
				.eq(UserOrder::getTenantId, AuthUtil.getTenantId())
				.eq(UserOrder::getUserId, user.getId())
				.eq(UserOrder::getThirdOrder, deliveryApplyId));
			if (listOrder == null || listOrder.size() < 1) {
				Integer number = Integer.parseInt(params.get("quantity").toString());
				// 商品信息
				StoreProduct storeProduct = storeProductService.getOne(Wrappers.<StoreProduct>lambdaQuery()
					.eq(StoreProduct::getTenantId, AuthUtil.getTenantId())
					.eq(StoreProduct::getZnCommodityId, params.get("commodityId").toString())//众鸟商品ID
					.last("limit 1"));
				// 生成订单
				UserOrder userOrder = userOrderService.insertMoneyOrder(user.getTenantId(),
					user.getId(),
					user.getRealName(),
					user.getAccount(),
					null,
					storeProduct,
					BigDecimal.valueOf(number),
					2,
					1,
					deliveryApplyId,
					"收货");
				// TODO 收货奖励
				userOrderService.confirmReceipt(userOrder);
			}
		}
		return R.data(returnJson.getInteger("status"), returnJson, returnJson.getJSONObject("content").get("msg") != null ? returnJson.getJSONObject("content").getString("msg") : "操作成功");
	}

	/**
	 * 查询买卖委托档位查询
	 */
	@GetMapping("/makerRecordSumInfo")
	@ApiOperationSupport(order = 34)
	@ApiOperation(value = "查询买卖委托档位查询")
	public R<JSONObject> makerRecordSumInfo(@ApiParam(value = "商品代码", required = true) @RequestParam String commodityId) {
		JSONObject returnJson = znApiUtils.makerRecordSumInfo(commodityId);
		logger.info("makerRecordSumInfo", returnJson.toJSONString());// 通用日志
		return R.data(returnJson.getInteger("status"), returnJson, returnJson.getJSONObject("content").get("msg") != null ? returnJson.getJSONObject("content").getString("msg") : "操作成功");
	}

	/**
	 * 查询商品可买量
	 */
	@GetMapping("/availableQuantity")
	@ApiOperationSupport(order = 35)
	@ApiOperation(value = "查询商品可买量")
	public R<JSONObject> availableQuantity(@ApiParam(value = "商品代码", required = true) @RequestParam String commodityId) {
		JSONObject returnJson = znApiUtils.availableQuantity(commodityId);
		logger.info("availableQuantity", returnJson.toJSONString());// 通用日志
		return R.data(returnJson.getInteger("status"), returnJson, returnJson.getJSONObject("content").get("msg") != null ? returnJson.getJSONObject("content").getString("msg") : "操作成功");
	}

	/**
	 * 物流信息查询
	 */
	@GetMapping("/deliveryTrace")
	@ApiOperationSupport(order = 36)
	@ApiOperation(value = "物流信息查询")
	public R<JSONObject> deliveryTrace(@ApiParam(value = "申请记录ID", required = true) @RequestParam String deliveryApplyId) {
		User user = userService.getById(AuthUtil.getUserId());
		JSONObject returnJson = znApiUtils.deliveryTrace(user.getZnToken(), user.getZnUserId(), deliveryApplyId);
		logger.info("deliveryTrace", returnJson.toJSONString());// 通用日志
		return R.data(returnJson.getInteger("status"), returnJson, "操作成功");
	}
	/***************************************************************************商品和卖出接口*****************************************************************************/

	/**
	 * 经理人协议交易数据导入
	 */
	@PostMapping("/protocolTradeImport")
	@ApiOperationSupport(order = 60)
	@ApiOperation(value = "经理人协议交易数据导入")
	public R<JSONObject> protocolTradeImport(@RequestParam MultipartFile file) {
		User user = userService.getById(AuthUtil.getUserId());
		JSONObject returnJson = znApiUtils.protocolTradeImport(user.getZnToken(), user.getZnUserId(), file);
		logger.info("protocolTradeImport", returnJson.toJSONString());// 通用日志
		if ("200".equals(returnJson.getString("status")) && returnJson.getJSONObject("content") instanceof JSONObject) {
			JSONObject content = returnJson.getJSONObject("content");
			JSONObject returnSubmitJson = znApiUtils.protocolTradeSubmit(user.getZnToken(), user.getZnUserId(), content.getString("responseValue"));
		}
		return R.data(returnJson.getInteger("status"), returnJson, returnJson.getJSONObject("content").get("msg") != null ? returnJson.getJSONObject("content").getString("msg") : "操作成功");
	}

	/**
	 * 经理人导入数据提交
	 */
	@PostMapping("/protocolTradeSubmit")
	@ApiOperationSupport(order = 61)
	@ApiOperation(value = "经理人导入数据提交")
	public R<JSONObject> protocolTradeSubmit(@ApiParam(value = "批次号", required = true) @RequestBody String batchNo) {
		User user = userService.getById(AuthUtil.getUserId());
		JSONObject returnJson = znApiUtils.protocolTradeSubmit(user.getZnToken(), user.getZnUserId(), batchNo);
		logger.info("protocolTradeSubmit", returnJson.toJSONString());// 通用日志
		return R.data(returnJson.getInteger("status"), returnJson, returnJson.getJSONObject("content").get("msg") != null ? returnJson.getJSONObject("content").getString("msg") : "操作成功");
	}

	/**
	 * 经理人协议交易查询
	 */
	@GetMapping("/managerListPc")
	@ApiOperationSupport(order = 62)
	@ApiOperation(value = "经理人协议交易查询")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "pageNum", value = "当前页码", paramType = "query", required = false, dataType = "String"),
		@ApiImplicitParam(name = "pageSize", value = "页面大小,传0时查询全部数据", paramType = "query", required = false, dataType = "String")
	})
	public R<JSONObject> managerListPc(@ApiIgnore @RequestParam Map<String, Object> params) {
		User user = userService.getById(AuthUtil.getUserId());
		JSONObject returnJson = znApiUtils.managerListPc(user.getZnToken(), user.getZnUserId(), params);
		logger.info("managerListPc", returnJson.toJSONString());// 通用日志
		return R.data(returnJson.getInteger("status"), returnJson, "操作成功");
	}

	/**
	 * 客户协议交易待确认列表查询
	 */
	@GetMapping("/unconfirmedList")
	@ApiOperationSupport(order = 63)
	@ApiOperation(value = "客户协议交易待确认列表查询")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "commodity", value = "商品（商品代码或名称）", paramType = "query", required = false, dataType = "String"),
		@ApiImplicitParam(name = "managerId", value = "经理人编号", paramType = "query", required = false, dataType = "String"),
		@ApiImplicitParam(name = "managerNickName", value = "经理人昵称", paramType = "query", required = false, dataType = "String"),
		@ApiImplicitParam(name = "offset", value = "查询偏移量，正值查询新增，负值查询过去数据", paramType = "query", required = true, dataType = "int"),
		@ApiImplicitParam(name = "standard", value = "查询基准号，本服务中定义为充值编号", paramType = "query", required = false, dataType = "String")
	})
	public R<JSONObject> unconfirmedList(@ApiIgnore @RequestParam Map<String, Object> params) {
		User user = userService.getById(AuthUtil.getUserId());
		JSONObject returnJson = znApiUtils.unconfirmedList(user.getZnToken(), user.getZnUserId(), params);
		logger.info("unconfirmedList", returnJson.toJSONString());// 通用日志
		return R.data(returnJson.getInteger("status"), returnJson, "操作成功");
	}

	/**
	 * 协议交易确认
	 */
	@PostMapping("/protocolTradeConfirm")
	@ApiOperationSupport(order = 64)
	@ApiOperation(value = "协议交易确认")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "commodityId", value = "商品编码", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "quantity", value = "数量", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "applyId", value = "申请编号", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "protocolTradeConfirmVO", value = "{\"addressId\":0,\"applyId\":0,\"bankId\":0,\"bankNO\":\"string\",\"payType\":0,\"tradeType\":0,\"type\":\"confirm\"}", paramType = "query", required = true, dataType = "String")
	})
	public R<JSONObject> protocolTradeConfirm(@ApiIgnore @RequestBody Map<String, Object> params) {
		User user = userService.getById(AuthUtil.getUserId());
		JSONObject protocolTradeConfirmVO = (JSONObject) JSONObject.toJSON(params.get("protocolTradeConfirmVO"));
		JSONObject returnJson = znApiUtils.protocolTradeConfirm(user.getZnToken(), user.getZnUserId(), params.get("applyId").toString(), protocolTradeConfirmVO);
		logger.info("protocolTradeConfirm", returnJson.toJSONString());// 通用日志
		if ("200".equals(returnJson.getString("status")) && returnJson.getJSONObject("content") instanceof JSONObject) {
			//直接挂单
			Map<String, Object> tradeSaleParams = new HashMap<>();
			tradeSaleParams.put("commodityId", params.get("commodityId"));
			tradeSaleParams.put("quantity", params.get("quantity"));
			JSONObject returnTradeSaleJson = znApiUtils.tradeSale(user.getZnToken(), user.getZnUserId(), tradeSaleParams);
		}
		return R.data(returnJson.getInteger("status"), returnJson, returnJson.getJSONObject("content").get("msg") != null ? returnJson.getJSONObject("content").getString("msg") : "操作成功");
	}

	/**
	 * 挂单
	 */
	@PostMapping("/tradeSale")
	@ApiOperationSupport(order = 65)
	@ApiOperation(value = "挂单")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "commodityId", value = "商品代码", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "quantity", value = "数量", paramType = "query", required = true, dataType = "String"),
		@ApiImplicitParam(name = "price", value = "价格", paramType = "query", required = false, dataType = "String")
	})
	public R<JSONObject> tradeSale(@ApiIgnore @RequestBody Map<String, Object> params) {
		User user = userService.getById(AuthUtil.getUserId());
		JSONObject returnJson = znApiUtils.tradeSale(user.getZnToken(), user.getZnUserId(), params);
		logger.info("tradeSale", returnJson.toJSONString());// 通用日志
		return R.data(returnJson.getInteger("status"), returnJson, returnJson.getJSONObject("content").get("msg") != null ? returnJson.getJSONObject("content").getString("msg") : "操作成功");
	}

	/**
	 * 查询发布
	 */
	@GetMapping("/makerRecordList")
	@ApiOperationSupport(order = 66)
	@ApiOperation(value = "查询发布")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "bsFlag", value = "买卖标志（1买2卖）", paramType = "query", required = false, dataType = "String"),
		@ApiImplicitParam(name = "commodity", value = "商品（商品代码）", paramType = "query", required = false, dataType = "String"),
		@ApiImplicitParam(name = "endCreateTime", value = "结束日期 格式:2020-08-08", paramType = "query", required = false, dataType = "String"),
		@ApiImplicitParam(name = "offset", value = "查询偏移量，正值查询新增，负值查询过去数据", paramType = "query", required = true, dataType = "int"),
		@ApiImplicitParam(name = "standard", value = "查询基准号，本服务中定义为充值编号", paramType = "query", required = false, dataType = "String"),
		@ApiImplicitParam(name = "startCreateTime", value = "开始日期 格式:2020-08-08", paramType = "query", required = false, dataType = "String"),
		@ApiImplicitParam(name = "status", value = "状态 orderStatus（1：未成交 2：已成交 3：已撤单）", paramType = "query", required = false, dataType = "String")
	})
	public R<JSONObject> makerRecordList(@ApiIgnore @RequestParam Map<String, Object> params) {
		User user = userService.getById(AuthUtil.getUserId());
		JSONObject returnJson = znApiUtils.makerRecordList(user.getZnToken(), user.getZnUserId(), params);
		logger.info("makerRecordList", returnJson.toJSONString());// 通用日志
		JSONObject returnJsonHis = znApiUtils.makerRecordListHis(user.getZnToken(), user.getZnUserId(), params);
		if (returnJson.getJSONObject("content").getJSONArray("list") == null) {
			returnJson.getJSONObject("content").put("list", returnJsonHis.getJSONObject("content").getJSONArray("list"));
		} else {
			if (returnJsonHis.getJSONObject("content").getJSONArray("list") != null) {
				returnJson.getJSONObject("content").getJSONArray("list").addAll(returnJsonHis.getJSONObject("content").getJSONArray("list"));
			}
		}
		return R.data(returnJson.getInteger("status"), returnJson, "操作成功");
	}
}
